package com.itheima.rpc.client.discovery.zk;

import com.itheima.rpc.cache.ServiceProviderCache;
import com.itheima.rpc.client.discovery.RpcServiceDiscovery;
import com.itheima.rpc.provider.ServiceProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @desc
 * @author:ivan.liu
 */
@Component
@Slf4j
public class ZkRpcServiceDiscovery implements RpcServiceDiscovery {

    @Autowired
    private ClientZKit zKit;

    //采用gavage的LoadingCache缓存
    @Autowired
    private ServiceProviderCache cache;

    @Override
    public void serviceDiscovery() {
        //获取zk的所以注册信息
        List<String> serviceList = zKit.getServiceList();
        if(serviceList!=null&&!serviceList.isEmpty()){
            for (String serviceName : serviceList) {
                //获取某一接口下的所以实例
                List<ServiceProvider> serviceProviderList = zKit.getServiceInfos(serviceName);
                //缓存到本地
                cache.put(serviceName,serviceProviderList);
                //注册删除事件的监听
                zKit.subscribeZKEvent(serviceName);
                log.info("从zk中拉取到注册信息，服务名为：{}，服务地址为：{}",serviceName,serviceProviderList);
            }
        }
    }
}
